import path from 'path';
import fs from 'fs';

import {fileURLToPath,pathToFileURL} from 'url';
import {dirname} from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const useMiddleware = (app) => {
  const files = fs.readdirSync(__dirname);
  files.forEach(async file => {
    let absolutePath = path.resolve(__dirname, file);
    absolutePath = pathToFileURL(absolutePath);
    if (fs.lstatSync(absolutePath).isDirectory()) return;
    if (file === 'index.js') return;
    // const middleware = require(absolutePath);
    const {default:middleware} = await import(absolutePath);
    if (typeof middleware !== 'function') return;
    middleware(app);
  })
}

export default useMiddleware;

